<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width:75vw">
      <ExamNavBar :examId="examId" :semesterId="semesterId" />

      <div v-if="errorMessage" class="error-message">
        <p>{{ errorMessage }}</p>
      </div>
       <div class="filter-section">
          <div class="filter-options">
            <p>批阅状态：</p>
            <label><input type="radio" v-model="filters.markStatus" value="all"> 全部</label>
            <label><input type="radio" v-model="filters.markStatus" value="0"> 未批阅</label>
            <label><input type="radio" v-model="filters.markStatus" value="1"> 已批阅</label>
          </div>
          <div class="filter-options">
            <p>提交状态：</p>
            <label><input type="radio" v-model="filters.submitStatus" value="all"> 全部</label>
            <label><input type="radio" v-model="filters.submitStatus" value="1"> 已提交</label>
            <label><input type="radio" v-model="filters.submitStatus" value="0"> 未提交</label>
          </div>
          <div class="filter-options">
            <p>分班查看：</p>
            <label><input type="radio" v-model="selectedDivision" value="all"> 全部</label>
            <label v-for="d in divisionList" :key="d.division_id">
              <input type="radio" v-model="selectedDivision" :value="d.division_name"> 
              {{ d.division_name }}
            </label>
          </div>
        </div>

      <!-- 学生答题列表 -->
      <div class="student-table-section">
        <div class="table-header" style="display: flex;justify-content: flex-end;align-items: center;margin-bottom: 20px;">
          <input v-model="searchTerm" placeholder="姓名/学号" @keyup.enter="loadData" class="search-input"/>
          <button @click="loadData" class="search-button">搜索</button>
        </div>

        <table class="student-table">
          <thead>
            <tr>
              <th>序号</th><th>姓名</th><th>学号</th><th>分班</th>
              <th>开始答卷时间</th><th>提交答卷时间</th><th>最终成绩</th><th>提交状态</th><th>批阅状态</th><th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="(item, index) in filteredData"
              :key="item.stu_exam_id"
              :class="{ 'row-unsubmit': item.submit_status === 0 }">
              <td>{{ index + 1 }}</td>
              <td>{{ item.student.username }}</td>
              <td>{{ item.student.stu_number || '--' }}</td>
              <td>{{ item.semDivison?.division_name ?? '--' }}</td>  <!-- 添加空值判断 -->
              <td>{{ formatTime(item.start_time) }}</td>
              <td>{{ item.submit_time ? formatTime(item.submit_time) : '--' }}</td>
              <td class="text-green">
                {{ item.get_score ?? '--' }}
              </td>
              <td>
                <span
                  :class="[
                    'pill',
                    item.submit_status === 1 ? 'pill-green' : 'pill-gray'
                  ]">
                  {{ item.submit_status === 1 ? '已提交' : '未提交' }}
                </span>
              </td>
               <td>
                <span
                  :class="[
                    'pill',
                    item.mark_status === 1 ? 'pill-green' : 'pill-orange'
                  ]">
                  {{ item.mark_status === 1 ? '已批阅' : '未评阅' }}
                </span>
              </td>
              <td>
                <button
                  v-if="item.submit_status === 1"
                  class="action-btn"
                  @click="handleReview(item)">
                  批阅
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <PagiNation 
          :currentPage="currentPage"
          :totalPages="totalPages"
          @page-change="currentPage = $event"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted,defineAsyncComponent } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import { fetchExamAnswerList, fetchDivisionList } from '@/services/api';

const AsyncExamNavBar = defineAsyncComponent(() => 
  import('@/components/ExamNavBar.vue')
);
export default {
  name: 'ExamDetail',
  components: { 
    ExamNavBar: AsyncExamNavBar,
    PagiNation: defineAsyncComponent(() => 
      import('@/components/PagiNation.vue')
    )
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const answerList = ref([]);
    const divisionList = ref([]);
    const currentPage = ref(1);
    const itemsPerPage = 10;
    const searchTerm = ref('');
    const errorMessage = ref('');
    const selectedDivision = ref('all');

    const filters = ref({
      markStatus: 'all',
      division: 'all',
      submitStatus: 'all'
    });

    const loadData = async () => {
      try {
        const params = {
          exam_id: route.params.examId,
          division: filters.value.division === 'all' ? null : filters.value.division,
          mark_status: filters.value.markStatus === 'all' ? null : filters.value.markStatus,
          submit_status: filters.value.submitStatus === 'all' ? null : filters.value.submitStatus,
        };

          const res = await fetchExamAnswerList(params);
          answerList.value = res.data.status === 1 ? res.data.data : [];
        } catch (err) {
          errorMessage.value = '数据加载失败';
        }
      };
        watch(searchTerm, (newVal) => {
    if (newVal === '') loadData();
  });

    const loadDivisions = async () => {
      try {
        const res = await fetchDivisionList(route.params.semesterId);
        divisionList.value = res.data.data || [];
      } catch (err) {
        console.error('分班加载失败:', err);
      }
    };

    const formatTime = (timeStr) => timeStr?.replace(' ', 'T').slice(0, 16).replace('T', ' ') || '--';

    const filteredData = computed(() => {
        return answerList.value.filter(item => {
          const divisionMatch = selectedDivision.value === 'all' || 
            item.semDivison?.division_name === selectedDivision.value;
          
          // 新增姓名/学号搜索过滤
          const searchTermLower = searchTerm.value.toLowerCase();
          const nameMatch = item.student.username.toLowerCase().includes(searchTermLower);
          const numberMatch = item.student.stu_number?.toLowerCase().includes(searchTermLower);
          
          return divisionMatch && (nameMatch || numberMatch);
        });
      });

    const totalPages = computed(() => Math.ceil(answerList.value.length / itemsPerPage));
    const handleReview = (item) => {
      router.push({
        path: `/exam/${route.params.semesterId}/${route.params.examId}/answer-review`, 
        query: {
          stu_exam_id: item.stu_exam_id,
          paper_id: localStorage.getItem('currentPaperId'),
          mark_status: item.mark_status,
        }
      });
    };


    watch(filters, loadData, { deep: true });
    onMounted(() => {
      loadDivisions();
      loadData();
    });

    return {
      examId: route.params.examId,
      semesterId: route.params.semesterId,
      errorMessage,
      filteredData,
      currentPage,
      totalPages,
      searchTerm,
      filters,
      divisionList,
      formatTime,
      loadData,
      selectedDivision,
      handleReview
    };
  }
};
</script>

<style scoped>
.pill{
  display:inline-block;
  padding:3px 14px;
  border-radius:999px;
  font-size:12px;
  line-height:18px;
  min-width:40px;  
  text-align:center;
}

.pill-green  { border: #29ad48c3 1px solid;color: #29ad48c6; } 
.pill-gray   { border: rgb(115, 115, 115) 1px solid;color:#6d6d6d; } 
.pill-orange { border: rgb(115, 115, 115) 1px solid;color:#6d6d6d; }
.row-unsubmit:hover .action-btn{
  opacity:0 !important;
  visibility:hidden !important;
}

.text-green { 
  color:#28a745 !important;
  }
.row-unsubmit:hover .action-btn{
  opacity:0 !important;
  visibility:hidden !important;
}
.container {
  width: 100vw;
  background: #F9F9F9;
  min-height: 100vh;
  padding: 20px;
  padding-top: 0px;
}

/* 统一筛选区域样式 */
.filter-section {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  padding: 0 30px;
  color: #535353;
  padding-top: 20px;
}

.filter-options {
  display: flex;
  gap: 15px;
  align-items: center;
  font-size: 14px;
}

/* 统一表格样式 */
.student-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.student-table th {
  background-color: #F6F7F9;
  font-size: 14px;
  font-weight: normal;
  border-bottom: 1px solid rgba(221, 221, 221, 0.453);
  padding: 12px;
  text-align: center;
  color: #535353;
}

.student-table td {
  color: #696969;
  padding: 12px;
  text-align: center;
  font-size: 14px;
  border-bottom: 1px solid rgba(221, 221, 221, 0.453);
  background-color: #FFFFFF;
}

.student-table tr:hover {
  background-color: #f9f9f9;
}

/* 统一搜索框样式 */
.search-input {
  padding: 8px 12px;
  margin-right: 10px;
  width: 250px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.search-button {
  padding: 8px 16px;
  background-color: #2f57a7;
  color: white;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}

.search-button:hover {
  background-color: #2a4d8f;
}

/* 统一操作按钮样式 */
.action-btn {
  background-color: #1e90ff;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: opacity 0.3s ease;
}

.action-btn:hover {
  background-color: #1c86ee;
}

/* 添加按钮渐显效果 */
.student-table tr td:last-child {
  width: 120px;
}

.student-table tr .action-btn {
  opacity: 0;
  visibility: hidden;
}

.student-table tr:hover .action-btn {
  opacity: 1;
  visibility: visible;
}

/* 错误提示保持原样 */
.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 10px;
  margin: 20px 0;
  border-radius: 4px;
}
.student-table-section{
    background-color: #ffffff;
    padding: 20px 30px;
    margin-bottom: 20px;
}
</style>
